import { Injectable, Session } from '@nestjs/common';
import { CreateLoginDto } from './dto/create-login.dto';
import { UpdateLoginDto } from './dto/update-login.dto';

import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/entities/user/user.entity';
import { BusinessException } from 'src/common/exceptions/business.exception.filter';

import { Cache } from 'cache-manager';
import { RedisService } from 'src/db/redis/redis.service';
import { ConfigService } from '@nestjs/config';

// import { File } from './file.model';
// import { seq } from '@nestjs/sequelize';
import * as multer from 'multer';
import * as path from 'path';
import * as svgCaptcha from 'svg-captcha'
@Injectable()
export class LoginService {
    private readonly cacheManager: Cache
    constructor(
        @InjectRepository(User)
        private readonly userRepository: Repository<User>,
        private redisService: RedisService,
        private readonly configService: ConfigService,
        // private sequelizeService: SequelizeService
    ) { }

    async addUser(user?: User) {
        return await this.userRepository.save({ name: 'cyp', phone: '12345678901', sex: '1', password: 'cyp926...', avatar: '' });
    }
    async getUser() {
        let total = await this.userRepository.count();
        let list = await this.userRepository.find()
        return { total, list }
    }
    // 登录接口
    async toLogin(data) {
        const { name, password } = data
        if (!name || !password) {
            throw new BusinessException({ code: 400, message: "参数错误" })
        }
        try {
            // 查询用户
            let user = await this.userRepository.findOne({ where: { name: name } });


            console.log(await this.redisService.get("Value"));
            await this.redisService.set(`${user.user_id}&${user.name}&${user.phone}`, '6266');
            this.redisService.getHello()

            if (user) {
                return user
            }
            return { message: '用户名或密码有误！' }
        } catch (error) {
            throw new BusinessException(error)
        }
    }
    // 获取验证码
    getCode() {
        const captcha = svgCaptcha.create({

            size: 5,
            ignoreChars: 'OoIl',
            noise: 2,
            background: '#cc9966', //背景颜色
            color: false,
            width: 100,
            height: 40

        });

        return { img: captcha.data }; // aptcha.data  返回的是svg图
    }
    async createFile(file: Express.Multer.File) {
        console.log(file);
        return '--'
    }
}
